<template>
  <div class="saveUpdate">
    <el-dialog :close-on-click-modal="false"
      :title="id"
      :visible.sync="showDialog"
      @close="$emit('update:showUpdate', false)"
      :showUpdate="showUpdate"
      width="500px"
    >
      <el-form :model="DetailInfo" ref="saveChn" label-width="130px" size="mini">
        <dialog-wrapper :MaxWidth="400">
          <el-form-item label="关联商户：" prop="mch_id" :rules="[{ required: true, message: '商户不能为空'}]">
            <el-select v-model="DetailInfo.mch_id" clearable placeholder="选择关联商户"
                       @change="changeMchName">
              <el-option
                v-for="item in MerchantsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="用户ID："
            prop="user_id"

            :rules="[{ required: true, message: '玩家ID不能为空'}]"
          >
            <el-input v-model="DetailInfo.user_id" placeholder="请输入用户ID"></el-input>
          </el-form-item>
          <el-form-item
            label="到账金额："
            prop="recharge_amount"
            :rules="[{ required: true, message: '到账金额不能为空'},{ type: 'number', message: '到账金额必须为数字值'}]"
          >
            <el-input v-model.number="DetailInfo.recharge_amount" placeholder="请输入订单金额"></el-input>
          </el-form-item>
          <el-form-item
            label="支付方式："
            prop="pay_type"

          >
            <el-select
              v-model="DetailInfo.pay_type"
              clearable
              placeholder="选择用户使用的支付方式"
              @change="changeReceiptAddresses"
            >
              <el-option
                v-for="(item,index) in payType"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="收款账号："
            prop="receipt_address_id"
          >
            <el-select
              v-model="DetailInfo.receipt_address_id"
              clearable
              placeholder="选择收款账号"
              @change="receiptAddresschange"
            >
              <el-option
                v-for="(item) in receipt_addresses"
                :key="item.id"
                :label="item.text"
                :value="item.id+''"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="充值金额："
            prop="real_amount"
            :rules="is_auto_arrival?[{ required: true, message: '支付金额不能为空'},{ type: 'number', message: '金额必须为数字值'}]:[]"
          >
            <el-input v-model.number="DetailInfo.real_amount" placeholder="自助收款时必填"></el-input>
          </el-form-item>
        </dialog-wrapper>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:showUpdate', false)" size="small">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="saveAddDetail" size="small">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import DialogWrapper from "@/components/DialogWrapper";
  import {addUserOrder, getReceiptAddresses, getAgencyReceiptDetail} from "@/api";
  import {FormarOrderMethodType} from "../../utils/CommonJs";
  import {useVcode} from "../../utils/CommonJs";
  import {queryFilter} from '@/utils/patch'

  export default {
    components: {DialogWrapper},
    data() {
      return {
        setbank: false,
        showDialog: this.showUpdate,
        loading: false,
        DetailInfo: {},
        relus: [],
        payType: [
          {id: 1, name: "支付宝"},
          {id: 2, name: "微信"},
          {id: 5, name: "银行卡"},
          {id: 4, name: "信用卡"},
          {id: 3, name: "花呗"}
        ],
        receipt_addresses: [],
        is_auto_arrival: false,
        dialogVisible: false,
        spanHtml: '',
        mch_name: '',
        receipt_name: ''
      };
    },
    props: {
      showUpdate: {
        type: Boolean,
        default: false
      },
      id: {
        type: Number
      },
      AgencyType: {
        type: Object
      },
      settleCycle: {
        type: Object
      },
      MerchantsList: {
        type: Array
      }
    },
    created() {
      this.mchidDefaultValue();
    },
    methods: {
      receiptAddresschange(val) {
        this.receipt_addresses.forEach(item => {
          if (item.id == val) {
            this.receipt_name = ''
            this.receipt_name = item.text
            this.is_auto_arrival = item.auto_arrival;
          }
        });
      },
      mchidDefaultValue() {
        if (this.MerchantsList.length == 1) {
          this.DetailInfo.mch_id = this.MerchantsList[0].id;
        }
      },
      changeMchName(val) {
        this.MerchantsList.forEach(item => {
          if (item.id === val) {
            this.mch_name = item.name
          }
        })
        console.log(this.mch_name)
      },
      saveAddDetail() {
        this.$refs.saveChn.validate(valid => {
          if (valid) {
            let params = Object.assign({}, this.DetailInfo, {
              real_amount: this.DetailInfo.real_amount
                ? this.DetailInfo.real_amount * 100
                : null,
              recharge_amount: this.DetailInfo.recharge_amount * 100
            });
            for (let key in params) {
              if (params[key] === null) {
                delete params[key];
              }
            }
            params = queryFilter(params)
            addUserOrder(params).then(res => {
              if (res.status === 0) {
                this.$message({message: `订单创建成功`, type: "success"});
                this.dialogVisible = true
                console.log(this.mch_name)
                if ((this.mch_name.includes("WH") || this.mch_name.includes("XY")) && this.receipt_name.includes('银行卡')) {
                  getAgencyReceiptDetail(this.DetailInfo.receipt_address_id).then(res => {
                    if (res.status === 0) {
                      this.spanHtml = `收款银行:${this.$store.state.app.BankCode[res.data.bank_code]}&nbsp;\\r\\n
                    收款名称:&lt;copy&gt;${res.data.first_name + res.data.last_name}&lt;/copy&gt;&nbsp;\\r\\n
                    收款账号:&lt;copy&gt;${res.data.account}&lt;/copy&gt;\r\n
                `
                    }
                  })
                } else {
                  this.$emit("update:showUpdate", false);
                }
              }
            });
          }
        });
      },
      copyContent() {
        let Url2 = document.getElementById("copy_text").innerText;
        let oInput = document.createElement('input');
        oInput.value = Url2;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.className = 'oInput';
        oInput.style.display = 'none';
        alert('复制成功');
        this.$emit("update:showUpdate", false);
      },
      changeReceiptAddresses() {
        this.$set(this.DetailInfo, "receipt_address_id", null);
        let pay_type = this.DetailInfo.pay_type;
        if (pay_type !="") {
          this.receipt_addresses = [];
          getReceiptAddresses(
            Object.assign(this.DetailInfo, {
              page_no: 1,
              page_size: 100,
              pay_type: pay_type,
              status: true
            })
          ).then(res => {
            if (res.status === 0) {
              res.data.items = Array.from(res.data.items).filter(p => {
                return p.status === true;
              });
              res.data.items.forEach(item => {
                let lable = "";
                //先判断是否有nickname，如果有说明是支付宝个人商户，
                // 如果没有判断是否有mch_name
                if (item.nickname == null) {
                  let receipt_name = item.first_name + item.last_name;
                  lable =
                    item.id +
                    "-" +
                    FormarOrderMethodType(item.receipt_type) +
                    "-" +
                    (receipt_name != 0
                      ? receipt_name + "-" + item.account
                      : item.mch_name);
                } else {
                  lable =
                    item.id +
                    "-" +
                    FormarOrderMethodType(item.receipt_type) +
                    "-" +
                    item.nickname +
                    "-" +
                    item.account;
                }
                this.receipt_addresses.push(
                  Object.assign({
                    id: item.id,
                    text: lable,
                    auto_arrival: item.auto_arrival
                  })
                );
              });
            }
          });
        }
      }
    },
    watch: {
      showUpdate() {
        this.showDialog = this.showUpdate;
      }
    }
  };
</script>
<style scoped>
  .el-input-number /deep/ .el-input__inner {
    text-align: left !important;
  }
</style>


